package com.ec.bl.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ec.api.domain.dto.CreateBillRequest;
import com.ec.bl.domain.dto.BillQueryDTO;
import com.ec.api.domain.po.Bill;
import com.ec.api.domain.po.BillDetail;
import com.ec.bl.domain.vo.BillDetailVO;
import com.ec.bl.domain.vo.BillQueryVO;
import com.ec.bl.domain.vo.BillWithDetailsVO;
import com.ec.bl.service.BillService;
import com.ec.common.domain.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/bills")
@RequiredArgsConstructor
public class BillController {

    private final BillService billService;

    /**
     * 分页查询账单
     */
    @GetMapping("/page")
    public Result<IPage<BillQueryVO>> queryBillPage(BillQueryDTO queryDTO) {
        try {
            IPage<BillQueryVO> page = billService.queryBillPage(queryDTO);
            return Result.ok(page);
        } catch (Exception e) {
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 根据ID查询账单详情
     */
    @GetMapping("/{id}")
    public Result<BillWithDetailsVO> getBillById(@PathVariable Long id) {
        try {
            BillWithDetailsVO billDetails = billService.getBillWithDetails(id);
            if (billDetails == null) {
                return Result.error("账单不存在");
            }
            return Result.ok(billDetails);
        } catch (Exception e) {
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 根据账单ID查询账单详情明细（仅返回详情项）
     */
    @GetMapping("/{id}/details")
    public Result<List<BillDetailVO>> getBillDetails(@PathVariable Long id) {
        try {
            BillWithDetailsVO billDetails = billService.getBillWithDetails(id);
            if (billDetails == null) {
                return Result.error("账单不存在");
            }
            return Result.ok(billDetails.getDetails());
        } catch (Exception e) {
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    @PostMapping("/create")
    public Result<Long> createBill(@RequestBody CreateBillRequest request) {
        try {
            // 校验输入
            if (request == null || request.getBill() == null || request.getBillDetails() == null || request.getBillDetails().isEmpty()) {
                return Result.error("账单或账单详情不能为空");
            }
            Bill bill = request.getBill();
            List<BillDetail> billDetails = request.getBillDetails();
            if (bill.getElderlyUserId() == null || bill.getTotalAmount() == null || bill.getBillMonth() == null) {
                return Result.error("账单关键字段缺失");
            }

            // 调用服务层创建账单
            return billService.createBill(bill, billDetails);
        } catch (Exception e) {
            return Result.error("账单创建失败: " + e.getMessage());
        }
    }
}
